package day01;

/**
 * @author feng
 * @Date 2021/10/13 21:29
 * 两个线程交替打印1-100
 * 线程通信问题:注意共享数据
 * wait、notify只能用在同步代码块和同步方法当中
 */
public class CommunicationTest implements Runnable {
    private int number = 1;

    @Override
    public void run() {
        while (true) {
            synchronized (this) {
                 notify();
                if (number <= 100) {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+"=" + "num: " + number);
                    number++;
                    try {
                        //使用wait方法使线程进入阻塞状态
                        wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }else {
                    break;
                }
            }

        }
    }

    public static void main(String[] args) {
        CommunicationTest test = new CommunicationTest();
        Thread t1 = new Thread(test);
        Thread t2 = new Thread(test);
        t1.setName("t1");
        t2.setName("t2");
        t1.start();
        t2.start();

    }
}
